<template>
  <div class="app-container" style="height: 100%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="100px">
      <el-form-item label="质检任务号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入质检任务号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="productNo">
        <el-input
          v-model="queryParams.productNo"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源单号" prop="sourceNo">
        <el-input
          v-model="queryParams.sourceNo"
          placeholder="请输入来源单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态"  >
          <el-option
            v-for="dict in dict.type.quality_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['quality:qualityMainTask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange" :height="calcTableHeight"
              highlight-current-row @current-change="rowSelection" >
      <af-table-column label="质检任务号" align="center" prop="no"  width="220px"/>
      <af-table-column label="物料编号" align="center" prop="productNo"  width="150px"/>
      <af-table-column label="物料名称" align="center" prop="productName"  width="150px"/>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.quality_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <af-table-column label="检验数量" align="center" prop="quantity" />
      <el-table-column label="检验结果" align="center" prop="qualityResult" />
      <af-table-column label="处理方式" align="center" prop="processMode" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.quality_process_mode" :value="scope.row.processMode"/>
        </template>
      </af-table-column>
      <af-table-column label="退货数量" align="center" prop="returnQuantity" />
      <el-table-column label="检验完成时间" align="center" prop="finishTime"  width="152"/>
      <el-table-column label="检验员" align="center" prop="qualityUserName" min-width="100"/>
      <af-table-column label="来源单号" align="center" prop="sourceNo" width="180"/>
      <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="152"/>
      <el-table-column label="最后更新人" align="center" prop="updateBy"  min-width="100"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="152"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--   质检任务明细 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane label="质检任务明细" name="detailList">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs>

    <!-- 修改物料抽检比例对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物料编号" prop="productNo" >
          <el-input v-model="form.productNo" placeholder="请输入物料编号"  :disabled=disabled />
        </el-form-item>
        <el-form-item label="物料名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入物料名称" :disabled=disabled />
        </el-form-item>
        <el-form-item label="抽检比例(%)" prop="qualityRatio">
          <el-input v-model="form.qualityRatio" placeholder="请输入抽检比例">
          <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { getMainTaskPage, delBomInfo } from "./api/productBom";
import { listProduct,getProduct,updateProduct} from "@/api/basic/product";
import { getToken } from "@/utils/auth";
import detailPage from "../qualityTaskDetail/index";
import { isEmpty, isQualityFour} from '@/utils/validate';

export default {
  name: "productBom",
  dicts: ['quality_task_status','quality_process_mode'],
  mixins:[mixins],
  components: { detailPage },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      selectionRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据表格数据
      bomList: [],
      // 物料列表
      productList: [],
      ynList: [
        {
          id:0,
          label:'是',
          value:'Y'
        },
        {
          id:1,
          label:'否',
          value:'N'
        }
        ],
      // 物料列表
      bomTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      disabled: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceNo:null,
        no: null,
        searchQualityItem:'Y',
        orderStatus: null,
        customerNo: null,
        customerName: null,
        workOrderNo: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/quality/qualityTaskDetail/importData"
      },
      // 表单参数
      form: {},
      //页面下方明细的选项
      activeTab:'detailList',
      //传递给订单详情的数据
      orderData:{},
      rules: {
        qualityRatio: [
          { required: true, message: "抽检比例不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                if (value <= 100) {
                  callback();
                } else {
                  callback('抽检比例不能大于100');
                }
              } else {
                callback('请输入数字，保留4位小数');
              }

            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getListCustomer();
    this.getList();
  },
  methods: {
    handleTabClick(value){
      console.log(value)
    },
    getListCustomer(){
      listProduct({pageNum:1,pageSize:0}).then(response => {
        this.productList = response.rows;
      });
    },
    /** 查询单据列表 */
    getList() {
      this.loading = true;
      this.rowSelection({});
      this.queryParams.qualityType = 'IQC';
      getMainTaskPage(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.bomList.forEach((row) => {
          if (row.qualityRatio) {
            row.qualityRatio = row.qualityRatio + '%';
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 修改抽检比例操作 */
    handleUpdate(row) {
      this.disabled=true;
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "设置抽检比例";
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.no)
      this.single = selection.length!==1
      this.selectionRows = selection
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //行选择
    rowSelection(row){
      this.orderData = row;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料BOM导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.qualityType = 'IQC';
      this.download('quality/qualityMainTask/export', {
        ...this.queryParams, ids: this.ids
      }, `来料检管理_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
        const a = document.createElement('a');
        a.href = `${process.env.BASE_URL}static/file/物料质检项导入模板.xlsx` //'./static/file/物料BOM导入模板.xlsx';
        a.click();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
